# -*- coding: UTF-8 -*-
# ---------------------------------------------------------
# @Author : Bingo
# @Time   : 2021/3/26 21:46
# @File   : a.py  
# ---------------------------------------------------------
# There is no bug, have a great day. Please start your code.
import subprocess
import ctypes
import sys
import os
import logging
from logging import RootLogger
from logging.handlers import RotatingFileHandler


class MyLog(RootLogger):
    """
    format常用格式说明
    %(levelno)s: 打印日志级别的数值
    %(levelname)s: 打印日志级别名称
    %(pathname)s: 打印当前执行程序的路径，其实就是sys.argv[0]
    %(filename)s: 打印当前执行程序名
    %(funcName)s: 打印日志的当前函数
    %(lineno)d: 打印日志的当前行号
    %(asctime)s: 打印日志的时间
    %(thread)d: 打印线程ID
    %(threadName)s: 打印线程名称
    %(process)d: 打印进程ID
    %(message)s: 打印日志信息
    """
    # __instance = None
    #
    # def __new__(cls, *args, **kwargs):
    #     if cls.__instance is None:
    #         cls.__instance = super().__new__(cls)
    #     return cls.__instance

    def __init__(self, **kwargs):
        level = kwargs.get("level", logging.INFO)
        super().__init__(level)

        formatter = kwargs.get("formatter")

        if formatter is None:
            formatter = logging.Formatter(
                "%(asctime)s %(levelname)s %(filename)s[%(funcName)s][line:%(lineno)d]: %(message)s")

        self.log_file = os.path.join("log", "record.log")
        if not os.path.exists(os.path.dirname(self.log_file)):
            os.makedirs(os.path.dirname(self.log_file))
        self.formatter = formatter
        self.add_to_my_handler()

    def add_to_my_handler(self):
        # 文件日志
        file_handle = RotatingFileHandler(filename=self.log_file, maxBytes=1024 * 1024 * 10, encoding="utf8")
        file_handle.setFormatter(self.formatter)
        self.handlers.append(file_handle)

        # 打印台输出日志
        stream_handle = logging.StreamHandler()
        stream_handle.setFormatter(self.formatter)
        self.handlers.append(stream_handle)


# 构造自己的日志记录
logger = MyLog(level=logging.INFO)


class CMD(object):
    """
    运行windows shell 命令
    """
    __instance__ = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance__ is None:
            cls.__instance__ = super().__new__(cls, *args, **kwargs)
        return cls.__instance__

    @staticmethod
    def is_admin():
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except Exception as e:
            logger.error("Error: ", e)
            return False

    def run_cmd(self, cmd):
        cmd_list = [cmd] if isinstance(cmd, str) else cmd

        if self.is_admin:
            for c in cmd_list:
                result_status, result_str = subprocess.getstatusoutput(c)
                logger.info(f"CMD>>>>> {c}, status: {result_status}, {result_str}")
                return result_status, result_str
        else:
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)


if __name__ == "__main__":
    # cmds = ["net start redis", "net stop redis"]
    # cmd_instance = CMD()
    # cmd_instance.run_cmd(cmds)
    pass
